<!-- 活动分享配置模块 -->
<template>
  <a-form
    ref="formRef"
    class="form"
    layout="horizontal"
    labelAlign="left"
    :hideRequiredMark="false"
    :colon="false"
    :labelCol="{ span: 24 }"
    :wrapperCol="{ span: 24 }"
    :model="model"
    :rules="props.isDetail ? [] : formRules"
  >
    <!-- 表单顶部插槽，定制表单顶部 -->
    <slot name="formTop" />
    <a-form-item label="活动名称" name="activityName" :wrapper-col="{ span: 12 }">
      <a-input v-model:value="model['activityName']" :disabled="props.isDetail" placeholder="不能超过20个汉字" />
    </a-form-item>
    <a-form-item v-if="formRules.litePath" label="游戏类型" name="litePath" :wrapper-col="{ span: 24 }">
      <a-radio-group v-model:value="model['litePath']" :disabled="props.isDetail" :options="gamePathOptions" />
    </a-form-item>
    <a-form-item label="活动时间" name="activityTime" :wrapper-col="{ span: 12 }">
      <a-range-picker
        :disabled="props.isDetail"
        :value="model['activityTime']"
        value-format="YYYY-MM-DD HH:mm:ss"
        :show-time="{ defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('23:59:59', 'HH:mm:ss')] }"
        :disabledDate="(currentDate) => currentDate && currentDate < dayjs().endOf('day').subtract(1, 'day')"
        @change="handleActivityTimeChange"
      />
    </a-form-item>
    <a-form-item label="活动说明" name="remark" :wrapper-col="{ span: 24 }">
      <a-textarea v-model:value="model['remark']" :disabled="props.isDetail" :rows="4" placeholder="请输入活动说明" />
      <span class="gz-tip-text">回车换行</span>
    </a-form-item>
    <a-form-item label="机构" name="agentNo" :wrapper-col="{ span: 12 }">
      <GzTreeSelect ref="gzThreeRef" v-model:value="model['agentNo']" :disabled="props.isDetail" />
    </a-form-item>
    <template v-if="model['agentNo']">
      <a-form-item label="微信公众号" name="wxOfficalAppId" :wrapper-col="{ span: 12 }">
        <a-select v-model:value="model['wxOfficalAppId']" :options="officialList" placeholder="请选择微信公众号" :disabled="props.isDetail" />
      </a-form-item>
      <a-form-item label="微信小程序" name="wxMiniProgramAppId" :wrapper-col="{ span: 12 }">
        <a-select v-model:value="model['wxMiniProgramAppId']" :options="miniProgramList" placeholder="请选择微信小程序" :disabled="props.isDetail" />
      </a-form-item>
    </template>
    <a-form-item v-if="model['agentNo'] && formRules.imgUrl" label="公众号素材图片" name="imgUrl" :wrapper-col="{span: 24}">
      <!-- <GzUpload v-model:src="model['imgUrl']" :disabled="props.isDetail" bizType="activity" />
      <span class="gz-tip-text">建议图片尺寸大小：520*416</span> -->
      <a-select v-model:value="model['imgUrl']" :options="officialMaterialsList" placeholder="请选择公众号素材图片" :disabled="props.isDetail" />
    </a-form-item>
    <a-form-item label="活动图片" name="activityImg" :wrapper-col="{span: 24}">
      <GzUpload v-model:src="model['activityImg']" :disabled="props.isDetail" bizType="activity" />
    </a-form-item>
    <a-form-item label="出资方" name="payAuthId" :wrapper-col="{span: 12}">
      <a-select
        v-model:value="model['payAuthId']"
        :disabled="props.isDetail"
        allowClear
        placeholder="请选择出资方"
        :field-names="{ label: 'ifName', value: 'payAuthId' }"
        :options="props.payAuthList"
      />
    </a-form-item>
    <a-form-item v-if="formRules.entryway" label="流量入口" name="entryway" :wrapper-col="{ span: 24 }">
      <a-checkbox-group v-model:value="model['entryway']" :disabled="props.isDetail">
        <a-row>
          <a-col :span="8">
            <a-checkbox value="0">小程序首页</a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="1">机构运营工具入口</a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="2">公众号渠道码</a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="3">广告</a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="4">商家活动入口</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-form-item>
    <template v-if="model['entryway']?.includes('0') && model['entryway']?.includes('2')">
      <a-form-item label="小程序页面副路由" name="litePath2" :wrapper-col="{ span: 12 }">
        <a-input v-model:value="model['litePath2']" disabled placeholder="请输入小程序页面副路由" />
      </a-form-item>
      <a-form-item label="活动副页面主图" name="activityImg2" :wrapper-col="{ span: 24 }">
        <GzUpload v-model:src="model['activityImg2']" :disabled="props.isDetail" />
      </a-form-item>
    </template>
    <a-form-item label="下级机构是否可见" name="isNextView" :wrapper-col="{ span: 24 }">
      <a-radio-group v-model:value="model['isNextView']" :disabled="props.isDetail">
        <a-radio :value="0">不可见</a-radio>
        <a-radio :value="1">可见</a-radio>
      </a-radio-group>
    </a-form-item>
    <!-- 表单底部插槽，定制表单底部 -->
    <slot name="formBottom" />
  </a-form>
</template>

<script setup>
import { defineProps, defineEmits, ref, defineExpose, onMounted, watch,inject } from 'vue'
import{$getProxyList,$getAgentWxList,$apiGetMaterialImgList} from '@/api/activityManage/activityCreate/index'
import { useVModel } from '@/utils/useVModel.js'
import dayjs from 'dayjs'

const emits = defineEmits(['update:modelValue'])

// 接收父组件的活动模板申请数据
let activityTemplateDataRef = inject('activityTemplateData')
let activityTemplateData = activityTemplateDataRef.value


const props = defineProps({
  // 表单绑定值
  modelValue: {
    type: Object,
    default: () => ({})
  },
  // 是否是详情
  isDetail: {
    type: Boolean,
    default: false
  },
  // 出资方列表
  payAuthList: {
    type: Array,
    default: () => []
  },
  // 表单校验规则 使用当前组件时可以根据具体情况自定义 默认全部必填
  rules: {
    type: Object,
    default: () => ({})
  }
})

// 表单规则（总） 默认所有字段必填 根据具体活动 某些字段可以不填 需要在组件挂载时合并传递过来的规则
const formRules = ref({
  activityName: [ { required: true, message: '请输入活动名称', trigger: 'blur' } ],
  activityTime: [ { required: true, message: '请选择活动时间', trigger: 'change' } ],
  agentNo: [ { required: true, message: '请选择机构', trigger: ['blur','change'] } ],
  wxOfficalAppId: [ { required: true, message: '请选择微信公众号', trigger: ['blur','change'] } ],
  wxMiniProgramAppId: [ { required: true, message: '请选择微信小程序', trigger: ['blur','change'] } ],
  remark: [ { required: true, message: '请输入活动说明', trigger: 'blur' } ],
  activityImg: [ { required: true, tigger: ['blur','change'], message: '请上传活动图片' } ],
  // imgUrl: [ { required: true, tigger: ['blur','change'], validator: () => !vdata.saveObject.imgUrl ? Promise.reject('请上传公众号素材') : Promise.resolve() } ],
  // litePath2: [ { required: true, message: '请输入小程序页面副路由', trigger: 'blur' } ],
  activityImg2: [ { required: true, message: '请上传活动副页面主图', trigger: 'blur' } ],
  isNextView: [{ required: true, message: '请选择下级机构是否可见', trigger: 'blur' }],
   hasBlacklist: [{ required: true, message: '请选择限不限制黑名单', trigger: ['blur'] }],
  blacklistRuleIdList: [{ required: true, message: '黑名单规则至少选择一个', trigger: ['blur'] }],
})

const model = useVModel(props, 'modelValue', emits)

// 表单实例
const formRef = ref()

// 传递表单默认值
onMounted(() => {
  // emits('update:modelValue', props.modelValue)
  // 合并规则 以传递规则为准 主要用于部分活动并非所有字段都需要校验
  Object.assign(formRules.value, props.rules)
})

// 游戏 对应 小程序路径
const gamePathOptions = [
  { label: '大转盘', value: '/pagesActivity/wheel/index' },
  { label: '刮刮乐', value: '/pagesActivity/scratchCard/index' },
  { label: '砸金蛋', value: '/pagesActivity/goldenEggs/goldenEggs' },
  { label: '翻翻乐', value: '/pagesActivity/flipMusic/flipMusic' },
]

// 查询机构小程序/公众号列表接口  0微信公众号   1微信小程序 
const officialList = ref([])
const miniProgramList = ref([])
async function getAgentWxList(agentNo){
  const [ res1, res2,res3 ] = await Promise.all([$getAgentWxList({ agentNo, type: 0 }),$getAgentWxList({ agentNo, type: 1 }),$apiGetMaterialImgList({activityTemplateNo:activityTemplateData.activityTemplateNo})])
  officialList.value = res1.map(item => ({ label: item.name, value: item.appId }))
  miniProgramList.value = res2.map(item => ({ label: item.name, value: item.appId }))
}

// 获取公众号素材列表
const officialMaterialsList = ref([])
async function getOfficialMaterialsList(){
  $apiGetMaterialImgList({activityTemplateNo:activityTemplateData.activityTemplateNo}).then(res=>{
    console.log(res,111111)
  })
}

getOfficialMaterialsList()

// getAgentWxList('41000122')

// 监听机构变化 重新请求小程序/公众号列表
watch(() => props.modelValue.agentNo, async (newVal) => {
  if (newVal) {
    getAgentWxList(newVal)
  }
})

/**
 * 活动时间变化事件
 * @param {*} e 
 */
function handleActivityTimeChange(e) {
  // 活动时间变化自动处理开始时间结束时间
  const [startTime, endTime] = e
  emits('update:modelValue',{...props.modelValue, startTime, endTime, activityTime: e})
}

// 表单校验事件
async function validateFields(fields) {
  return new Promise((resolve, reject) => {
    formRef.value.validateFields(fields).then(() => {
      resolve()
    }).catch(err => {
      reject(err)
    })
  })
}
// 表单重置事件
function clearValidate() {
  if (formRef.value !== undefined) {
    formRef.value.clearValidate()
  }
}
// 暴露表单校验事件
defineExpose({
  validateFields,
  clearValidate
})

</script>

<style lang="less" scoped>
.form{
  width: 80%;
  margin-left: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number) {
  width: 100%;
}
</style>